const BlackLists = require('./BlackLists')


//添加到黑名单
exports.addBlack=async (myuid,uid) => {

    let lists=await getList(myuid)

    if(!lists){
        let lists_=[]
        lists_.push(uid)

        let obj={
            myuid,
            lists:lists_
        }

        let blacks=new BlackLists(obj)
        await blacks.save();

        return {
            myuid,
            lists:lists_
        }
    }

    else{
        lists.push(uid)
        let updata_list = [...new Set(lists)];
        updateBlack(myuid,updata_list )
        return {
            myuid,
            updata_list
        }
    }

}


//更新黑名单
const updateBlack=async (myuid,updata_list) => {

    let lists_new={myuid,lists:updata_list}

    await BlackLists.update({myuid},lists_new)

    return ''
}
exports.updateBlack=updateBlack



//删除黑名单
exports.delBlack=async (myuid,uid) => {

    let res=await isInBlack(myuid,uid)

    if(res.flag){
        let lists= res.lists
        let uid_index= res.index

        lists.splice(uid_index,1)

        let updata_list = [...new Set(lists)];
        updateBlack(myuid,updata_list)

        return updata_list
    }

    return '黑名单中不存在该用户'
}


//是否存在于黑名单中
const isInBlack=async (myuid,uid) => {

    let lists=await getList(myuid)

    if(!lists){
        return {
            flag:false
        }
    }
    else{

        let res={
            flag:false
        }
        for(let i=0; i<lists.length; i++){

            if(lists[i]==uid){
                res={
                    flag:true,
                    index: i,
                    lists:lists
                }
              break
            }
        }
       return res
    }
}
exports.isInBlack=isInBlack



//检查对方是否在自己的黑名单中(双方都检查)
exports.checkBlackAll=async (myuid,uid) => {

    let myuid_in=await checkBlack(myuid,uid)

    let uid_in=await checkBlack(uid,myuid)

    return {
        myuid_in_blacklist:myuid_in.in_blacklist,
        uid_in_blacklist:uid_in.in_blacklist
    }
}


//检查对方是否在自己的黑名单中
const checkBlack=async (myuid,uid) => {

    let lists=await getList(uid)
    if(!lists){
        return {
            in_blacklist:false,
        }
    }
    else{

        let res={
            in_blacklist:false,
        }
        for(let i=0; i<lists.length; i++){

            if(lists[i]==myuid){
                res={
                    in_blacklist:true,
                }
                break
            }
        }
        return res
    }
}
exports.checkBlack=checkBlack



//保存黑名单
exports.saveBlack=async (myuid,uid) => {

    let obj={
        myuid:myuid-0,
        list:[]
    }

    let blacks=new BlackLists(obj)
    await blacks.save();

    return ''

}


//获取黑名单列表
const getList=async (myuid) => {

    let obj=await BlackLists.findOne({myuid})

    if(obj){
        return obj.lists
    }
    else{
        return null
    }
}
exports.getList=getList



